//
//  RdbSubscribeReceiptRequest.swift
//  rdb-led-banner
//  验证交易收据
//  Created by radiobox3 on 2025/4/17.
//

import StoreKit
import Alamofire

class RdbSubscribeReceiptRequest: NSObject,SKRequestDelegate{
    
    static let shared = RdbSubscribeReceiptRequest()
    
    var reciptRequestCompleted: SubscribeCompletion?
    
    lazy var receiptRequest: SKReceiptRefreshRequest = {
        let request = SKReceiptRefreshRequest()
        request.delegate = self
        return request
    }()
    
    func refreshReceipt(_ completion: SubscribeCompletion?)  {
        self.reciptRequestCompleted = completion
        if NetworkReachabilityManager.default?.isReachable == true {
            self.receiptRequest.start()
        } else {
            self.reciptRequestCompleted?(false, nil)
        }
    }
    
    func getReceiptBase64String() -> String? {
        guard let url = Bundle.main.appStoreReceiptURL else {
            return nil
        }
        do {
            let receiptData = try Data(contentsOf: url, options: .alwaysMapped)
            return receiptData.base64EncodedString()
        } catch {
            return nil
        }
    }
    
    
    //MARK: - SKProductsRequestDelegate
    func requestDidFinish(_ request: SKRequest) {
        self.reciptRequestCompleted?(true, nil)
        print("recipt request finish")
        
    }

    func request(_ request: SKRequest, didFailWithError error: any Error) {
        self.reciptRequestCompleted?(false, ["errorCode": (error as NSError).code])
        print("recipt request fail")
    }
    
}
